package com.mh.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import static com.mh.server.HttpProtocolUtil.getResponseNotFound;
import static com.mh.server.HttpProtocolUtil.getResponseOk;

/**
 * @author MH
 * @since 2021-10-27
 */
public class Response {

    private final OutputStream outputStream;

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public void outputOkHtml(String body) throws IOException {
        outputHtml(getResponseOk(body, body.length()).getBytes());
    }

    public void outputHtml(byte[] body) throws IOException {
        this.outputStream.write(body);
    }

    public void outputStaticResource(String url) throws IOException {
        ClassLoader classLoader = Response.class.getClassLoader();
        InputStream resource;
        if (url.equals("/")) {
            resource = classLoader.getResourceAsStream("index.html");
        } else {
            resource = classLoader.getResourceAsStream(url.startsWith("/") ? url.substring(1) : url);
        }

        if (resource == null) {
            this.outputStream.write(getResponseNotFound().getBytes());
            return;
        }

        int count = 0;
        while(count == 0){
            count = resource.available();
        }

        this.outputStream.write(getResponseOk("", count).getBytes());

        byte[] bytes = new byte[1024];
        int len = -1;
        while ((len = resource.read(bytes)) != -1) {
            this.outputStream.write(bytes, 0, len);
            this.outputStream.flush();
        }
    }
}
